package com.daodaofun.dao.impl;

import com.daodaofun.dao.BaseDao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

public  class BaseDaoImpl<T>  implements BaseDao<T> {
    // 定义类对象
    private final Class<T> clz;

    // 完成类对象的赋值
    public BaseDaoImpl() {
        this.clz = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass())
                .getActualTypeArguments()[0];
    }


    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public Serializable save(T t) {
        return getSession().save(t);
    }

    @Override
    public void update(T t) {
        getSession().update(t);
    }

    @Override
    public void saveOrUpdate(T t) {
        getSession().saveOrUpdate(t);
    }

    @Override
    public void delete(T t) {
        getSession().delete(t);
    }

    @Override
    public T get(Serializable id) {

        Session session = getSession();
        return session.get(clz,id);
    }

    @Override
    public T load(Serializable id) {
        Session session = getSession();
        return session.load(clz,id);
    }

    @Override
    public List<T> listAll() {
        return getSession().createQuery("from " + clz.getSimpleName()).list();
    }

    @Override
    public List<T> listPage(int pageNum, int pageSize) {
        return getSession().createQuery("from " + clz.getSimpleName()).setFirstResult((pageNum-1)*pageSize).setMaxResults(pageSize).list();
    }

    @Override
    public long count() {
        return (long) getSession().createQuery("select count(*) from " + clz.getSimpleName()).uniqueResult();
    }


    public Session getSession(){
        return sessionFactory.getCurrentSession();
    }
}
